using System;
using System.Linq;
using System.Web;
using Toast.Filters;
using Toast.HttpHandlers;

namespace Toast.HttpModules
{
    public class ToastHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.ReleaseRequestState += OnReleaseRequestState;
            context.PostMapRequestHandler += ContextPostMapRequestHandler;
        }

        #endregion

        static void OnReleaseRequestState(object sender, EventArgs e)
        {
            //TODO: Not sure this is the best way 
            if (HttpContext.Current.Response.ContentType.Contains("text/html") && RequestContentTable.Contents.Count > 0)
            {
                var toinclude = RequestContentTable.Contents.Where(x => x.InjectIf == null || x.InjectIf());
                
                var key = RequestPackageCache.Insert(toinclude);

                var pic = new PositionalInjectionDictionary(toinclude, key);

                HttpContext.Current.Response.Filter = new ContentInjectionFilter(HttpContext.Current.Response.Filter, pic);
            }
        }

        static void ContextPostMapRequestHandler(object sender, EventArgs e)
        {
            var context = ((HttpApplication) sender).Context;
            if (context.Request.Url.PathAndQuery.Contains(Core.ToastCore.HANDLER_FILENAME))
                context.Handler = new ToastHttpHandler();
        }
    }
}